package com.javalong.mir.common.util;

import java.io.IOException;
import java.util.UUID;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛工具类
 * @author javalong
 */
public class QiNiuUtils {

	public final static String ACCESS_KEY = "sqv-wgaANF4zU7EYLDvV9AQSiuACZlT7O87Vs9xw";
	
	public final static String SECRET_KEY = "HLhOY6SlMefmyLsOWCmM1p0EY8yckKw6KE7hoyBy";
	//要上传的空间
	public final static String  bucketname = "mirs";
	 //密钥配置
	  static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	  //创建上传对象
	  static UploadManager uploadManager = new UploadManager();

	  //简单上传，使用默认策略，只需要设置上传的空间名就可以了
	  public static String getUpToken(){
	      return auth.uploadToken(bucketname);
	  }

	  public static String upload(String filepath) throws IOException{
	    try {
	     String uuid = UUID.randomUUID().toString();
	      //调用put方法上传
	      Response res = uploadManager.put(filepath,uuid ,getUpToken());
	      
	      if(res.statusCode==200){
	    	  return uuid;
	      }
	      } catch (QiniuException e) {
	          Response r = e.response;
	          // 请求失败时打印的异常的信息
	          System.out.println(r.toString());
	          try {
	              //响应的文本信息
	            System.out.println(r.bodyString());
	          } catch (QiniuException e1) {
	              //ignore
	          }
	      }    
	    return null;
	  }
	  
	  public static String upload(byte[] buffer) throws IOException{
		    try {
		     String uuid = UUID.randomUUID().toString();
		      //调用put方法上传
		      Response res = uploadManager.put(buffer,uuid ,getUpToken());

		      if(res.statusCode==200){
		    	  return uuid;
		      }
		      } catch (QiniuException e) {
		          Response r = e.response;
		          // 请求失败时打印的异常的信息
		          System.out.println(r.toString());
		          try {
		              //响应的文本信息
		            System.out.println(r.bodyString());
		          } catch (QiniuException e1) {
		              //ignore
		          }
		      }    
		    return null;
		  }
}
